import { Platform } from 'react-native';
import {
  Product,
  ProductPurchase,
  Purchase,
  PurchaseError,
  Subscription,
  SubscriptionAndroid,
  SubscriptionIOS,
  SubscriptionPurchase,
  clearTransactionIOS,
  endConnection,
  finishTransaction,
  flushFailedPurchasesCachedAsPendingAndroid,
  getAvailablePurchases,
  getProducts,
  getSubscriptions,
  initConnection,
  purchaseErrorListener,
  purchaseUpdatedListener,
  requestPurchase,
  requestSubscription,
} from 'react-native-iap';

import { memberAPI } from '@/api/memberAPI';
import { paymentAPI } from '@/api/paymentAPI';
import { APP_NAME } from '@/constants';
import { getPriceAndCurrency } from '@/hooks/subscription/utils';
import { getUserMemberInfo } from '@/utils';
/**
 * 支付服务
 */
export default class PayServer {
  static connectionStatus = false;
  private static instance: PayServer | null = null; // 静态变量保存单例实例

  private constructor() {}
  public static getInstance(): PayServer {
    // 如果实例不存在，则创建新实例并返回；如果实例已存在，则直接返回现有实例
    if (!PayServer.instance) {
      initConnection().then((res) => {
        console.log('PayServer: initConnection success:', res);
        PayServer.clearTransaction();
        PayServer.connectionStatus = true;
      });
      PayServer.instance = new PayServer();
    }
    return PayServer.instance;
  }

  /**
   * 清除幽灵订单（即已经失败但在 Play Store/App Store 缓存中仍标记为待处理的待处理付款）
   */
  public static async clearTransaction() {
    if (Platform.OS === 'android') {
      await flushFailedPurchasesCachedAsPendingAndroid();
    } else if (Platform.OS === 'ios') {
      await clearTransactionIOS();
    }
  }

  /**
   * 创建订单
   **/
  createOrder(props: {
    payMethod: '1' | '2' | '3' | '10' | '11';
    quantity: number;
    productCode: string;
    appAccountToken?: string;
  }) {
    if (Platform.OS === 'ios') {
      return paymentAPI.create_payment_order({ appName: APP_NAME, ...props });
    }
    return paymentAPI.create_payment_order_android({
      appName: APP_NAME,
      ...props,
    });
  }

  /** 获取所有产品 (从Apple Store/Google Play获取) */
  async getAllProducts(skus: string[]) {
    if (Platform.OS === 'android') {
      const androidSubscriptions = await getSubscriptions({ skus });
      const androidProducts = await getProducts({ skus });
      console.log('====================================');
      console.log('androidSubscriptions', androidSubscriptions);
      console.log('androidProducts', androidProducts);
      console.log('====================================');
      return [...androidSubscriptions, ...androidProducts];
    } else {
      return getProducts({ skus });
    }
  }

  public static IsProduct = (product?: Subscription | Product): product is Product => {
    if (!product) {
      return false;
    }
    if (Platform.OS === 'android') {
      const sub = product as SubscriptionAndroid;
      return ['inapp', 'iap'].includes(sub.productType);
    }
    const sub = product as Product;
    return ['inapp', 'iap'].includes(sub.type);
  };

  public static IsSubscription = (
    product?: Subscription | Product,
  ): product is Exclude<Subscription, 'SubscriptionAmazon'> => {
    if (!product) {
      return false;
    }
    if (Platform.OS === 'android') {
      const sub = product as SubscriptionAndroid;
      return ['sub', 'subs'].includes(sub.productType);
    }
    const sub = product as SubscriptionIOS;
    return ['sub', 'subs'].includes(sub.type);
  };

  /**
   * 获取产品列表(从服务器获取)
   */
  async getProductList() {
    const productList = await memberAPI.getProductList();

    const codes = productList.map((item) => item.code);

    const products = await this.getAllProducts(codes);

    productList.forEach((product) => {
      const payProduct = products.find((item) => item.productId === product.code);
      const priceAndCurrency = getPriceAndCurrency(payProduct);
      if (payProduct && priceAndCurrency) {
        product.details = priceAndCurrency;
      }
    });
    console.log('productList', productList);

    return productList;
  }

  /** 发起支付 */
  requestPurchase(params: {
    skus: string[];
    product: Subscription & Product;
    appAccountToken?: string;
    orderId?: Payment.PaymentOrderID;
  }) {
    if (this.isSubscription(params.product)) {
      console.log('订阅');
      return this.subscribeProduct(params.product, params.appAccountToken, params.orderId);
    } else if (this.isPermanent(params.product)) {
      console.log('购买');
      return this.purchaseProduct(params.product, params.skus, params.appAccountToken);
    }
  }

  /**
   * 判断是否订阅
   */
  isSubscription(product: Subscription & Product) {
    if (Platform.OS === 'android') {
      return ['sub', 'subs'].includes(product.productType);
    }
    return ['sub', 'subs'].includes(product.type);
  }

  /** 判断是否是永久产品 */
  isPermanent(product: Subscription & Product) {
    if (Platform.OS === 'android') {
      return ['iap', 'inapp'].includes(product.productType);
    }
    return ['iap', 'inapp'].includes(product.type);
  }
  /** 订阅产品 */
  subscribeProduct(product: Product & Subscription, appAccountToken?: string, orderId?: Payment.PaymentOrderID) {
    if (Platform.OS === 'android') {
      const productId = product.productId;
      const offerToken = product?.subscriptionOfferDetails?.[0]?.offerToken;
      return requestSubscription({
        sku: productId,
        ...(offerToken && {
          subscriptionOffers: [{ sku: productId, offerToken }],
          obfuscatedProfileIdAndroid: orderId,
          obfuscatedAccountIdAndroid: orderId,
        }),
        appAccountToken: appAccountToken,
      });
    } else if (Platform.OS === 'ios') {
      const productId = product.productId;
      return requestSubscription({
        sku: productId,
        appAccountToken: appAccountToken,
      });
    }
  }

  /** 购买产品（一次性支付）*/
  async purchaseProduct(product: Product, skus: string[], appAccountToken?: string, orderId?: Payment.PaymentOrderID) {
    return requestPurchase({
      sku: product.productId,
      skus: skus,
      appAccountToken: appAccountToken,
      obfuscatedAccountIdAndroid: orderId,
      obfuscatedProfileIdAndroid: orderId,
    });
  }

  /**
   * 关闭支付连接
   */
  endConnection() {
    PayServer.instance = null;
    return endConnection();
  }
  /**
   * 完成订单
   */
  async finishTransaction(purchase: ProductPurchase | SubscriptionPurchase) {
    await finishTransaction({ purchase });
  }

  /** 恢复购买 */
  async recoveryPurchaseRecord() {
    try {
      const purchases = await getAvailablePurchases();
      /** 按时间排序 */
      const transactionIdList = purchases.sort((a, b) => b.transactionDate - a.transactionDate);
      /** 根据最新的订单进行恢复 */
      await paymentAPI.restoreSubscription(transactionIdList[0].transactionReceipt);
      const memberInfo = await getUserMemberInfo();
      if (memberInfo && memberInfo.status && [3, 4, '3', '4'].includes(memberInfo.status)) {
        return memberInfo;
      }
      return false;
    } catch (error) {
      console.warn('恢复订阅出错', error);
      return false;
    }
  }

  /** 支付失败 */
  purchaseErrorListener(fn: (error: PurchaseError) => void) {
    return purchaseErrorListener(fn);
  }

  purchaseUpdatedListener(successCallback?: () => void) {
    return purchaseUpdatedListener((purchase: Purchase) => {
      // 支付凭证
      const receipt = purchase.transactionReceipt;
      if (receipt) {
        this.finishTransaction(purchase);
        PayServer.clearTransaction();
        if (successCallback) {
          successCallback();
        }
      }
    });
  }
}
